<template>
  <div class="public-filter">
    <collapse ref="collapse">
      <template v-slot:content>
        <div style="padding: 4px 20px 0;">
          <div class="flex form-inline justify-between no-wrap"
               style="padding: 0">
            <div class="left box flex">
              <div class="margin-r-20">
                <customized-switch style="width: 192px; height: 24px;margin-top:4px"
                                   :options="dateTypeOption"
                                   v-model="queryParams.dateType"
                                   @change="onChangeDateType" />
              </div>
              <div class="margin-r-20">
                <date-picker :format="format"
                             :clearable="false"
                             :editable="false"
                             :type="queryParams.dateType"
                             v-model="queryParams.dateRange"
                             :range="range"
                             placeholder="选择时间范围"
                             style="width: 240px"
                             @change="onChangeSelRange" />
              </div>
              <select-tooltip
                v-model="queryParams.workshop"
                :multiple="false"
                :options="locationOptions"
                v-if="isWorkshop"
                msg="所在车间"
              ></select-tooltip>
              <select-tree label="所在位置"
                           v-else
                           :sel-tree="queryParams.location"
                           class="margin-r-20"
                           ref="selectTree"
                           :tree-list="locationOptions"
                           node-key="hash"
                           @treeChange="onChangeTreeNode" />
              <select-tooltip v-model="queryParams.devices"
                              :multiple='true'
                              v-if="isShowDevices"
                              :options="devicesOption"
                              msg="设备"></select-tooltip>
              <fuzzy-search
                  v-model="queryParams.product"
                  title="产品"
                  v-if="isShowProduct"
                  :fuzzyFunc="fuzzyFunc"
                  fuzzyValue="number"
                  class="margin-r-20"
              ></fuzzy-search>
              <yz-input
                v-model.trim="queryParams.productSpec"
                v-if="isShowProductSpecs"
                class="q-mr-md"
                title="产品规格"
              />
            </div>
            <div class="flex no-wrap">
              <q-btn class="btn margin-r-10"
                     outline
                     dense
                     emit-value
                     map-options
                     options-dense
                     color="primary"
                     @click="onResetSearch()"
                     label="重置" />
              <q-btn class="btn"
                     unelevated
                     type="submit"
                     color="primary"
                     v-throttle
                     label="查询"
                     @click="onSearchData()" />
            </div>
          </div>
        </div>
      <slot></slot>
      </template>
    </collapse>
  </div>
</template>

<script>
import Collapse from 'src/components/collapse'
import CustomizedSwitch from 'src/components/customized-switch'
import SelectTree from 'src/components/select-tree'
import moment from 'moment'
import { getOrganize } from '../../../boot/tpm/equipment-record'
import { getDeviceIds } from '../../../boot/statistics/device-rate'
import { defaultSchemesClearer } from '../../../assets/js/util'
import { getSearchMaterials } from 'src/boot/plan/plant-plan'
import _ from 'lodash'
import GetPublicDate from './get-publice-date'
import { getWorkshops } from '../../../boot/job/process-order'
export default {
  name: 'public-filter',
  components: {
    CustomizedSwitch,
    SelectTree,
    Collapse
  },
  created () {
    if (this.isWorkshop) {
      this.getWorkshops()
    } else {
      this.getOrganize()
    }
  },
  mounted () {},
  props: {
    range: {
      type: Boolean,
      default: true
    },
    // 过滤是否绑定盒子的设备
    ifBuildBox: {
      type: Boolean,
      default: false
    },
    isWorkshop: {
      type: Boolean,
      default: false
    },
    isShowProduct: Boolean,
    isShowDevices: {
      type: Boolean,
      default: true
    },
    isShowProductSpecs: {
      type: Boolean,
      default: false
    },
    value: Object,
    init: Function // 初始化查询
  },
  watch: {
    value: {
      handler (newPro) {
        this.queryParams = newPro
      },
      immediate: true,
      deep: true
    },
    queryParams: {
      handler (newPro) {
        if (newPro.location?.hash) {
          newPro.workshopName = this.locationObj[newPro.location.hash]
        }
        this.$emit('input', newPro)
      },
      deep: true
    },
    'queryParams.workshop' (val) {
      if (val) {
        this.onChangeTreeNode(val)
      }
    }
  },
  data () {
    return {
      fuzzyFunc: getSearchMaterials,
      dateList: [
        {
          date: 'YYYY-MM-DD'
        },
        {
          week: this.range ? 'YYYY-MM-DD' : 'YYYY-ww'
        },
        {
          month: 'YYYY-MM'
        }
      ],
      dateClone: {
        date: this.range ? [moment(new Date())
          .subtract(6, 'days')
          .toDate(),
        new Date()] : new Date(),
        month: this.range ? [] : new Date(),
        week: this.range ? [] : new Date()
      },
      locationOptions: [], // 所在位置数据源
      devicesOption: [
        {
          label: '全部',
          value: 'all'
        }
      ], // 设备下拉数据
      dateTypeOption: [
        {
          value: 'date',
          label: ' 日 ',
          msg: '日视图下,日期范围最大不可超过60天',
          interval: 60
        },
        {
          value: 'week',
          label: ' 周 ',
          msg: '周视图下,日期范围最大不可超过10周',
          interval: 10
        },
        {
          value: 'month',
          label: ' 月 ',
          msg: '月视图下,日期范围最大不可超过24月',
          interval: 24
        }
      ],
      queryParams: {
        productSpec: '',
        dateRange: this.range ? [] : new Date()
      },
      materialNameOptions: [],
      oprofNum: 0,
      locationObj: {}
    }
  },
  computed: {
    format () {
      return _.find(this.dateList, this.queryParams.dateType)[this.queryParams.dateType]
    }
  },
  methods: {
    // 获取加工车间
    getWorkshops () {
      getWorkshops().then(res => {
        this.locationOptions = res.data
        if (this.locationOptions?.length > 0) {
          this.queryParams.workshop = this.locationOptions[0].value
        }
        this.init(this.queryParams)
      })
    },
    // 重置查询条件
    onResetSearch () {
      if (this.range) {
        this.queryParams.dateRange = [
          moment(new Date())
            .subtract(6, 'days')
            .toDate(),
          new Date()
        ]
        this.dateClone = {
          date: [moment(new Date())
            .subtract(6, 'days')
            .toDate(),
          new Date()],
          month: [],
          week: []
        }
      } else {
        Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
        Object.assign(this.dateClone, this.$options.data.call(this).dateClone)
      }
      this.queryParams.dateType = 'date'
      this.selectFirstLocation()
      // 产品
      this.queryParams.product = null
      this.queryParams.queryParams = ''
      this.queryParams.devices = ['all']
    },
    // 查询条件,分发给父组件
    onSearchData () {
      if (this.range && _.isEmpty(this.queryParams.dateRange)) {
        return this._Message('请选择日期范围', () => { this.queryParams.dateRange = [] })
      }
      this.$emit('onSearchData', this.queryParams)
    },
    // 改变日,周,月事件触发
    onChangeDateType () {
      this.queryParams.dateRange = this.dateClone[this.queryParams.dateType]
    },
    // 选择日期的判断逻辑
    onChangeSelRange () {
      if (!this.range) return
      if (this.queryParams.dateType === 'week' && this.queryParams.dateRange) {
        const s = moment(this.queryParams.dateRange[0]).startOf('week').toDate()
        const b = moment(this.queryParams.dateRange[1]).endOf('week').toDate()
        this.queryParams.dateRange = [s, b]
      }
      this.dateClone[this.queryParams.dateType] = _.cloneDeep(this.queryParams.dateRange)
      this.dateDialog()
    },
    // dateDialog 日期错误提示框
    dateDialog () {
      const getPublicDate = new GetPublicDate(
        this.queryParams.dateRange,
        this.queryParams.dateType
      )
      const member = _.find(
        this.dateTypeOption,
        v => v.value === this.queryParams.dateType
      )
      const isOpenDateTootip = getPublicDate._isLtDay(member.interval)
      if (isOpenDateTootip) {
        this._Message(member.msg, () => { this.queryParams.dateRange = [] })
      }
    },
    // 选择组织机构树节点 *
    onChangeTreeNode (val) {
      this.queryParams.devices = ['all']
      if (this.isWorkshop) {
        this.getDevices(val, 2)
      } else if (val.id && val.label && val.hash) {
        this.queryParams.location.id = val.id
        this.queryParams.location.level = val.level
        this.queryParams.location.label = val.label
        this.queryParams.location.hash = val.hash
        this.queryParams.station = null
        this.getDevices(val.id, val.level)
      } else {
        this.selectFirstLocation()
        this.queryParams.station = null
        // this.stationOptions = [this.defaultStationOption]
      }
    },
    // 获取组织下设备列表
    getDevices (schemeId, schemeLevel) {
      getDeviceIds(schemeId, schemeLevel, this.ifBuildBox).then(res => {
        const ret = res.data
        const member = ret.list.map(v => {
          const item = v
          item.label = `${v.name}(${v.assetNumber || '--'})`
          item.value = v.id
          return item
        })
        this.$emit('setOprofNum', ret.total)
        this.devicesOption = [
          {
            label: '全部',
            value: 'all'
          },
          ...member
        ]
      })
    },
    // 获取组织机构树
    getOrganize () {
      getOrganize().then(res => {
        // 去除 default 节点
        let clearTree = defaultSchemesClearer.clear(res.data)
        const obj = {}
        // 重新组织 tree
        clearTree.forEach(reorganize)

        function reorganize (node) {
          // 如果当前节点是工位，将 opname 挪到 label
          if (node.level === 5) {
            node.label = node.opname
          }
          obj[node.hash] = node.label

          // 为节点添加唯一键，用于 tree 组件标识唯一节点
          node.uniqueKey = node.level + ':' + node.id

          if (node.children instanceof Array) {
            node.children.forEach(reorganize)
          }
        }

        this.locationOptions = clearTree
        this.locationObj = obj
        this.selectFirstLocation()
        this.init(this.queryParams)
      })
    },
    // 选中第一个组织
    selectFirstLocation () {
      if (this.locationOptions.length === 0) {
        return
      }
      if (this.isWorkshop) {
        if (this.locationOptions?.length) {
          this.queryParams.workshop = this.locationOptions[0].value
        } else {
          this.queryParams.workshop = null
        }
      } else {
        const first = this.locationOptions[0]
        this.queryParams.location.id = first.id
        this.queryParams.location.level = first.level
        this.queryParams.location.label = first.label
        this.queryParams.location.hash = first.hash
        this.$refs.selectTree.setValue(this.queryParams.location)
        this.getDevices(first.id, first.level)
      }
    },
    _Message (msg, fn) {
      return this.$q
        .dialog({
          title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>${msg}</p>`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        }).onOk(fn)
    }
  }
}
</script>

<style scoped lang="stylus">
>>>.q-field--with-bottom{
  margin-bottom 0
}
</style>
